using System.Text;
using System.Text.Json;

namespace LicenseApp.Test;

/// <summary>
/// 授权码调试工具
/// </summary>
public static class LicenseDebugger
{
    /// <summary>
    /// 解析授权码内容（不验证签名）
    /// </summary>
    public static void AnalyzeLicenseCode(string licenseCode)
    {
        Console.WriteLine("=== 授权码分析 ===");
        Console.WriteLine();
        
        try
        {
            // 解码Base64
            var jsonBytes = Convert.FromBase64String(licenseCode);
            var jsonData = Encoding.UTF8.GetString(jsonBytes);
            
            Console.WriteLine("1. Base64解码成功");
            Console.WriteLine($"   JSON长度: {jsonData.Length} 字符");
            Console.WriteLine();
            
            // 解析JSON
            var jsonDoc = JsonDocument.Parse(jsonData);
            var root = jsonDoc.RootElement;
            
            Console.WriteLine("2. JSON解析成功");
            Console.WriteLine("   授权码内容:");
            
            if (root.TryGetProperty("StartDate", out var startDate))
            {
                Console.WriteLine($"   - 生效日期: {startDate.GetString()}");
            }
            
            if (root.TryGetProperty("Days", out var days))
            {
                Console.WriteLine($"   - 授权天数: {days.GetInt32()}");
            }
            
            if (root.TryGetProperty("AgvCount", out var agvCount))
            {
                Console.WriteLine($"   - AGV数量: {agvCount.GetInt32()}");
            }
            
            if (root.TryGetProperty("Signature", out var signature))
            {
                var sigStr = signature.GetString() ?? "";
                Console.WriteLine($"   - 签名长度: {sigStr.Length} 字符");
                Console.WriteLine($"   - 签名前缀: {sigStr.Substring(0, Math.Min(20, sigStr.Length))}...");
            }
            
            Console.WriteLine();
            Console.WriteLine("3. 完整JSON内容:");
            Console.WriteLine(jsonData);
            Console.WriteLine();
            
            // 计算有效期
            if (root.TryGetProperty("StartDate", out var start) && 
                root.TryGetProperty("Days", out var duration))
            {
                if (DateTime.TryParse(start.GetString(), out var startDateTime))
                {
                    var endDate = startDateTime.AddDays(duration.GetInt32());
                    var now = DateTime.Now;
                    var remaining = (endDate.Date - now.Date).Days;
                    
                    Console.WriteLine("4. 有效期分析:");
                    Console.WriteLine($"   - 开始日期: {startDateTime:yyyy-MM-dd}");
                    Console.WriteLine($"   - 结束日期: {endDate:yyyy-MM-dd}");
                    Console.WriteLine($"   - 当前日期: {now:yyyy-MM-dd}");
                    Console.WriteLine($"   - 剩余天数: {remaining}");
                    Console.WriteLine($"   - 状态: {(remaining >= 0 ? "有效" : "已过期")}");
                }
            }
            
        }
        catch (FormatException)
        {
            Console.WriteLine("❌ Base64解码失败 - 授权码格式不正确");
        }
        catch (JsonException ex)
        {
            Console.WriteLine($"❌ JSON解析失败: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"❌ 分析失败: {ex.Message}");
        }
        
        Console.WriteLine();
        Console.WriteLine("=== 分析完成 ===");
    }
    
    /// <summary>
    /// 测试授权码注册流程
    /// </summary>
    public static void TestLicenseRegistration(string licenseCode)
    {
        Console.WriteLine("=== 授权码注册测试 ===");
        Console.WriteLine();
        
        // 首先分析授权码
        AnalyzeLicenseCode(licenseCode);
        
        Console.WriteLine();
        Console.WriteLine("=== 注册流程测试 ===");
        
        // 检查是否有公钥
        var publicKeyPath = System.IO.Path.Combine(
            LicenseApp.Client.LicenseValidator.PATH, "public.xml");
        
        Console.WriteLine($"1. 检查公钥文件: {publicKeyPath}");
        
        if (System.IO.File.Exists(publicKeyPath))
        {
            Console.WriteLine("   ✅ 公钥文件存在");
            
            try
            {
                var publicKeyContent = System.IO.File.ReadAllText(publicKeyPath);
                Console.WriteLine($"   公钥长度: {publicKeyContent.Length} 字符");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"   ❌ 读取公钥失败: {ex.Message}");
            }
        }
        else
        {
            Console.WriteLine("   ❌ 公钥文件不存在");
            Console.WriteLine("   提示: 需要先设置公钥才能验证授权码");
        }
        
        Console.WriteLine();
        Console.WriteLine("2. 尝试注册授权码...");
        
        try
        {
            bool result = LicenseApp.Client.LicenseManager.RegisterLicense(licenseCode);
            Console.WriteLine($"   注册结果: {(result ? "✅ 成功" : "❌ 失败")}");
            
            if (result)
            {
                var status = LicenseApp.Client.LicenseManager.GetCurrentStatus();
                Console.WriteLine($"   授权状态: {status.Status}");
                Console.WriteLine($"   状态消息: {status.Message}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"   ❌ 注册异常: {ex.Message}");
        }
        
        Console.WriteLine();
        Console.WriteLine("=== 测试完成 ===");
    }
}
